﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System;

namespace block_explorer
{
    class FPSCounter : DrawableGameComponent
    {
        SpriteFont mFont;
        SpriteBatch mSpriteBatch;

        int mFrames;
        int mFrameRate;
        TimeSpan mElapsedTime;

        int mDisplayWidth;
        int mDisplayHeight;

        public FPSCounter(Game game)
            :base(game)
        {
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        protected override void  LoadContent()
        {
            mFont = Game.Content.Load<SpriteFont>("ConsoleFont");
            mSpriteBatch = new SpriteBatch(GraphicsDevice);

            mDisplayWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
            mDisplayHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;

            base.LoadContent();
        }

        public override void  Update(GameTime gameTime)
        {
            mElapsedTime += gameTime.ElapsedGameTime;

            if (mElapsedTime.Seconds >= 1)
            {
                mElapsedTime -= TimeSpan.FromSeconds(1);
                mFrameRate = mFrames;
                mFrames = 0;
            }

            base.Update(gameTime);
        }

        public override void  Draw(GameTime gameTime)
        {
            ++mFrames;

            string txtFPS = string.Format("{0}", mFrameRate);
            Vector2 txtBounds = mFont.MeasureString(txtFPS);
            Vector2 position = new Vector2(mDisplayWidth - txtBounds.X, 0);

            mSpriteBatch.Begin();
            mSpriteBatch.DrawString(mFont, txtFPS, position, Color.White);
            mSpriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
